package org.qiyu.live.web.starter;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: 用户请求上下文
 * @Description: TODO
 * @Author zhangguangyan
 * @Date 2023/08/31/ 20:14:57
 * @Version 1.0
 */
public class QiyuRequestContext {


    private static final ThreadLocal<Map<Object, Object>> resources = new InheritableThreadLocalMap<>();

    public static void put(Object key, Object value) {
        if (key == null) {
            throw new IllegalArgumentException("key cannot be null");
        }
        if (value == null) {
            resources.get().remove(key);
            return;
        }
        resources.get().put(key, value);
    }

    public static Long getUserId() {
        Object result = get(RequestConstants.QIYU_USER_ID);
        return result == null ? null :
                Long.valueOf(String.valueOf(result));
    }

    private static Object get(Object key) {
        if (key == null) {
            throw new IllegalArgumentException("key cannot be null");
        }
        return resources.get().get(key);
    }

    public static void clear() {
        resources.remove();
    }

    //实现父子线程之间的线程本地变量传递
    private static final class InheritableThreadLocalMap<T extends Map<Object, Object>> extends InheritableThreadLocal<Map<Object, Object>> {
        @Override
        protected Map<Object, Object> initialValue() {
            return new HashMap();
        }

        @Override
        protected Map<Object, Object> childValue(Map<Object, Object> parentValue) {
            if (parentValue != null) {
                return (Map<Object, Object>) ((HashMap<Object, Object>) parentValue).clone();
            } else {
                return null;
            }
        }
    }
}